import { defineStore } from 'pinia';
import config from '@/config'
const { title } = config
import { useDynamicRoutes } from "./hooks/useDynamicRoutes"
import { login, logout, getInfo, menuListApi } from '@/api/user'
import router from "@/router"
import type { IMenu } from "@/types/base";
import type { ILoginFrom } from '@/types/login';
import { notification } from 'ant-design-vue';
export interface IUser {
  userId: number | string
  username: string;
}
export const useUserStore = defineStore('user', () => {

  const token = ref<string>('')
  const name = ref<string>('')
  const avatar = ref<string>('http://kaifa.crmeb.net/system/images/admin_logo.png')
  const roles = ref<string>('')
  const permissions = ref<string[]>([])
  const menus = ref<IMenu[]>([])
  const user = ref<Partial<IUser>>()

  function setAccessToken(accessToken: string) {
    token.value = accessToken
    sessionStorage.setItem('token', accessToken)
  }
  function getUserInfo() {
    return new Promise((resolve, reject) => {
      getInfo(token.value).then(res => {
        roles.value = res.roles
        name.value = res.account
        user.value = res
        permissions.value = res.permissions
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
  async function getMenuList() {
    let menusAll = await menuListApi()
    // userPermissions.value = permissions
    menus.value = menusAll.map(formatMenu)
    const dynamicRoute = useDynamicRoutes(menusAll)
    router.addRoute(dynamicRoute)
    // console.log(menuList.value)
    return dynamicRoute
  }
  async function userLogin(userInfo: ILoginFrom) {
    const data = await login(userInfo)
    if (data.token) {
      setAccessToken(data.token)
      const hour = new Date().getHours()
      const thisTime = hour < 8 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 18 ? '下午好' : '晚上好'
      notification.open({
        message: `欢迎登录${title}`,
        description: `${thisTime}！`
      })
      return data.token
    }
  }
  async function userlogout() {

    resetAll()
  }
  async function resetAll() {
    token.value = ''
    roles.value = ''
    name.value = ''
    permissions.value = []
    sessionStorage.setItem('token', '')
    router.push('/login')
  }
  return {
    userLogin,
    userlogout,
    token,
    menus,
    permissions,
    getMenuList,
    getUserInfo,
    user
  }
}, {
  persist: {
    paths: ['token']
  }
});


function formatMenu(menu: IMenu) {
  const { component, icon, id, childList, name, pid, isShow } = menu
  let children: IMenu[] = []
  if (childList && childList.length > 0) {
    children = childList.map(formatMenu)
  }
  return {
    name,
    icon,
    id,
    url: formatUrl(component),
    children,
    pid,
    isShow
  }
}

const URL_MAP = {
  'modules/oss/oss.html': 'modules/sys/oss.html',
  'modules/job/schedule.html': 'modules/sys/schedule.html'
}

function formatUrl(url: string | null) {
  if (url) {
    return (URL_MAP[url as keyof typeof URL_MAP] || url).replace('.html', '')
  } else {
    return ''
  }
}
